package com.fishleap.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.fishleap.bean.UpLoadResult;
import com.fishleap.config.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

@Service
public class FileUpLoadService {

    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient  ossClient;

    // 允许上传的格式  .pdf 是测试文件大小时使用
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};

    /**
     * 文件上传
     * @param multipartFile 表单文件
     * @return 响应类
     */
    public UpLoadResult upload(MultipartFile multipartFile){
        // 校验图片格式
        boolean  isLegal = false;
        for (String type:IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(multipartFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        //封装Result对象，并且将文件的byte数组放置到result对象中
        UpLoadResult upLoadResult = new UpLoadResult();
        if (!isLegal){
            upLoadResult.setStatus("error 文件类型不符合 请重新选择");
            return  upLoadResult;
        }
        System.out.println("file_size:"+multipartFile.getSize());
        //校验文件大小
        if(multipartFile.getSize()>1024*1024*5){
            upLoadResult.setStatus("error 文件超过5m 请重新选择");
            return  upLoadResult;
        }
        //文件新路径
        String fileName = multipartFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        //上传阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(multipartFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            upLoadResult.setStatus("error");
            return  upLoadResult;
        }
        upLoadResult.setStatus("done");
        upLoadResult.setName(aliyunConfig.getUrlPrefix()+filePath);
        upLoadResult.setUid(filePath);
        return  upLoadResult;
    }

    /**
     *   下载文件
     * @param os
     * @param objectName
     * @throws IOException
     */
    public void exportOssFile(OutputStream os, String objectName) throws IOException {
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
        // 读取文件内容。
        BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(os);
        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) != -1) {
            out.write(buffer, 0, lenght);
        }
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     * @return 响应类
     */
    public UpLoadResult  deleteFile(String filePath) {
        UpLoadResult upLoadResult = new UpLoadResult();

        try {
            if (!ossClient.doesObjectExist(aliyunConfig.getBucketName(),filePath)){
                upLoadResult.setStatus("删除的文件不存在");
                return  upLoadResult;
            }
            // 根据BucketName,文件路径删除文件
            ossClient.deleteObject(aliyunConfig.getBucketName(),filePath);
            upLoadResult.setStatus("删除文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            upLoadResult.setStatus("删除文件失败");
        }
        return  upLoadResult;
    }

    /**
     * 查看文件列表
     * @return
     */
    public List<OSSObjectSummary> list() {
        // 设置最大个数。
        final int maxKeys = 200;
        // 列举文件。
        ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(aliyunConfig.getBucketName()).withMaxKeys(maxKeys));
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        return sums;
    }

    // 生成不重复的文件路径和文件名
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
